package thread;

public class ProducerConsumer {

	public static void main(String[] args) {
		BaoziStack baoziStack = new BaoziStack();
		Producer p1 = new Producer(baoziStack);
		Consumer c1 = new Consumer(baoziStack);

		p1.start();
		c1.start();

	}
}

// 包子类
class Baozi {
	int id;

	public Baozi(int id) {
		this.id = id;
	}

	@Override
	public String toString() {
		return "包子  : " + id;
	}
}

// 包子筐
class BaoziStack {
	Baozi[] bz = new Baozi[10];
	int index = 0;

	// 装包子
	public synchronized void pushBZ(Baozi baozi) {
		if (index >= bz.length) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		bz[index] = baozi;
		index++;
		notify();
	}

	// 取包子
	public synchronized Baozi popBZ() {

		if (index <= 0) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		index--;
		Baozi baozi = bz[index];
		notify();
		return baozi;
	}
}

// 生产者:生产包子，放到包子筐里
class Producer extends Thread {

	private BaoziStack baoziStack;

	public Producer(BaoziStack baoziStack) {
		this.baoziStack = baoziStack;
	}

	@Override
	public void run() {
		// 生产包子（一天生产100个包子）
		for (int i = 1; i <= 100; i++) {
			Baozi baozi = new Baozi(i);
			System.out.println("生产者生产了一个包子ID为： " + i);
			baoziStack.pushBZ(baozi);
			try {
				sleep(50);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

// 消费者
class Consumer extends Thread {

	private BaoziStack baoziStack;

	public Consumer(BaoziStack baoziStack) {
		this.baoziStack = baoziStack;
	}

	@Override
	public void run() {
		// 一天的消费量为100个包子
		for (int i = 1; i <= 100; i++) {
			Baozi baozi = baoziStack.popBZ();
			System.out.println("消费者消费了一个包子ID为：" + baozi.id + "的包子");
			try {
				sleep(1500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

